#pragma once

#include <iostream>
#include <string>
#include <functional>
#include <unistd.h>
#include <sys/types.h> 
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <signal.h>
#include <cstring>
#include <cerrno>
#include <cstdlib>
#include "err.hpp"
#include "log.hpp"

namespace ns_server
{
    const uint16_t defaultport = 8089; 
    const int backlog = 32;
    using func_t = std::function<std::string(std::string)>;

    class TcpServer;
    struct ThreadData
    {
        int sock_;
        std::string clientip_;
        uint16_t clientport_;
        TcpServer* current_;

        ThreadData(const int& sock, std::string& clientip, uint16_t& clientport, TcpServer* current)
            :sock_(sock),clientip_(clientip), clientport_(clientport),current_(current)
        {}
    };

    class TcpServer
    {
    public: 
        TcpServer(func_t func, uint16_t port = defaultport)
            :port_(port)
            ,func_(func)
        {

        }

        void InitServer()
        {
            ///1.创建sock文件接口
            listensock_ = socket(AF_INET, SOCK_STREAM, 0);
            if(listensock_ == -1)
            {
                //std::cerr << "socket error" << strerror(errno) << std::endl;
                logMessage(Fatal, "create socket error, code: %d, error string: %s", errno, strerror(errno));
                exit(SOCKET_ERR);
            }
            logMessage(Info, "create socket success, code: %d, error string: %s", errno, strerror(errno));
            //2.bind
            struct sockaddr_in local;
            bzero(&local, sizeof(local));
            local.sin_family = AF_INET;
            local.sin_addr.s_addr = INADDR_ANY;
            local.sin_port = htons(port_);
            if(bind(listensock_, (struct sockaddr*)&local, sizeof(local)) == -1)
            {
                //std::cerr << "bind error" << strerror(errno) << std::endl;
                logMessage(Fatal, "bind socket error, code: %d, error string: %s", errno, strerror(errno));
                exit(BIND_ERR);
            }
            logMessage(Info, "bind socket success, code: %d, error string: %s", errno, strerror(errno));
            //3.监听
            if(listen(listensock_, backlog) == -1)
            {
                //std::cerr << "listen error" << strerror(errno) << std::endl;
                logMessage(Fatal, "listen socket error, code: %d, error string: %s", errno, strerror(errno));
                exit(LISTEN_ERR);
            }
            logMessage(Info, "listen socket success, code: %d, error string: %s", errno, strerror(errno));
        }

        void Start()
        {
            //signal(SIGCHLD, SIG_IGN); //ok, 我最后推荐的！
            // signal(SIGCHLD, handler); // 挥手，不太推荐
            
            while(1)
            {
                //4.获取链接s
                struct sockaddr_in client;
                socklen_t len = sizeof(client);
                int sock = accept(listensock_, (struct sockaddr*)&client, &len);
                if(sock == -1)
                {
                    //std::cerr << "accept error" << strerror(errno) << std::endl;
                    logMessage(Warning, "accept error, code: %d, error string: %s", errno, strerror(errno));
                    continue;
                }
                //提取client信息
                std::string clientip = inet_ntoa(client.sin_addr);
                uint16_t clientport = ntohs(client.sin_port);

                // std::cout << "连接成功" << sock << " from " << listensock_ << ", "
                //     << clientip << "-" << clientport << std::endl;
                logMessage(Info, "获取新连接成功: %d from %d, who: %s - %d",
                           sock, listensock_, clientip.c_str(), clientport);
                
                //开始业务处理
                //...
                //V1  只能一对一，主进程被卡在了处理业务上，只能等一个业务处理完了之后再回来接受另一个连接
                //service(sock, clientip, clientport);

                //V2.多进程处理
                // pid_t id = fork();
                // if(id < 0)
                // {
                //     close(sock);
                //     continue;
                // }
                // else if(id == 0)
                // {
                //     //child :父进程的fd，会被child继承。父子不会用同一张文件描述符表，子进程拷贝继承父进程的fd table;
                //     close(listensock_);//避免误操作
                //     if(fork() > 0) exit(0);
                //     // child已经退了，孙子进程在运行,去执行service函数，此时他是个孤儿进程,由OS管理
                //     service(sock, clientip, clientport);

                //     exit(0);
                // }
                
                // //等待-回收子进程
                // close(sock);
                // pid_t ret = waitpid(id, nullptr, 0); //阻塞的! waitpid(id, nullptr, WNOHANG);//不推荐
                // if(ret == id) std::cout << "wait child " << id << " success" << std::endl; 

                //V3.多线程
                pthread_t tid;
                ThreadData* data = new ThreadData(sock, clientip, clientport, this);
                pthread_create(&tid, nullptr, threadRoutine, data);
            }
        }
        static void* threadRoutine(void* args)
        {
            pthread_detach(pthread_self());
            ThreadData* td = static_cast<ThreadData*>(args);
            td->current_->service(td->sock_, td->clientip_, td->clientport_);
            delete td;
            return nullptr;
        }

        void service(const int sock, const std::string& clientip, const uint16_t& clientport)
        {   
            std::string clientname = clientip + "_" + std::to_string(clientport);
            while(1)
            {
                char buffer[1024];
                ssize_t n = read(sock, buffer, sizeof(buffer));
                if(n > 0)
                {
                    buffer[n] = 0;
                    std::string res = func_(buffer); // 进行回调
                    //std::cout << clientname << ">>> " << buffer << std::endl;
                    logMessage(Debug, "%s# %s", clientname.c_str(), clientname.c_str());

                    //发出响应
                    write(sock, res.c_str(), res.size());
                }
                else if(n == 0)
                {
                    // 对方将连接关闭了
                    close(sock);
                    //std::cout << clientname << " quit, me too" << std::endl;
                    logMessage(Info, "%s quit,me too", clientname.c_str());
                    break;
                }
                else {
                    close(sock);
                    //std::cerr << "read error: " << strerror(errno) << std::endl;
                    logMessage(Error, "read error, %d:%s", errno, strerror(errno));
                    break;
                }
            }
        }

        ~TcpServer()
        {

        }
    private:
        uint16_t port_;
        int listensock_;
        func_t func_;//任务处理的回调函数
    };
}
